<?php

namespace Home\Model;

use Think\Model;

class MsglogModel extends Model {
    function __construct() {

        //判断是否开启短信
        if (!C('msg_enabled')) {
            render('10008', '系统未开启短信服务');
        }
        if(!C('msg_pid') || !C('msg_key')){
            render('10009', '管理员未填写短信账号');
        }
		$msg_pid='';
		$msg_key='';
		$mall_config= M('mallConfig')->where(array('code IN ("msg_pid","msg_key")'))->select();
		
		if(is_array($mall_config)){
			foreach($mall_config as $mc){
				if($mc['code']=='msg_pid'){
					$msg_pid=$mc['value'];
				}
				if($mc['code']=='msg_key'){
					$msg_key=$mc['value'];
				}
			}
		}
        define('SMS_UID', $msg_pid);
        define('SMS_KEY', $msg_key);
    }
    /**
     * 
     * @param type $user_id   记录ID   为0 表示为系统发送消息
     * @param type $user_name  用户名
     * @param type $to_mobile  地址
     * @param type $content  内容
     * @return boolean
     */
    function send_msg($user_id, $user_name, $to_mobile, $smsText) {
        //验证是否为手机号
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $to_mobile)) {
            render('10003', '手机号码格式错误');
        }
        
        $ip = real_ip();
        if ($user_id == 0) {
            //发送验证码1分钟只能点击发送1次；
            $sql = "to_mobile = '{$to_mobile}' AND state > 0 AND time>" . (time() - 60);
            if (M('Msglog')->where($sql)->find()) {
                render('10005', '发送验证码1分钟只能点击发送1次');
            }
            //相同IP手机号码1天最多提交20次；
            $sql = "to_mobile = '{$to_mobile}' AND state > 0 AND time>" . (time() - 86400) . " AND ip='{$ip}'";
            if (M('Msglog')->where($sql)->count('id') >= 20) {
                render('10006', '相同IP手机号码1天最多提交20次');
            }
            //验证码短信单个手机号码30分钟最多提交10次；
            $sql = "to_mobile = '{$to_mobile}' AND state > 0 AND time>" . (time() - 3600);
            if (M('Msglog')->where($sql)->count('id') >= 10) {
                render('10007', '验证码短信单个手机号码30分钟最多提交10次');
            }
        }
        
        
        //发送短信
		$param=urlencode($smsText);
        $url = 'http://utf8.sms.webchinese.cn/?Uid=' . SMS_UID . '&Key=' . SMS_KEY . '&smsMob=' . $to_mobile . '&smsText=' . $param;
        $res = request_get($url);
                
        $add_msglog = array(
            'user_id' => $user_id,
            'user_name' => $user_name,
            'to_mobile' => $to_mobile,
            'content' => $smsText,
            'state' => $res,
            'time' => time(),
            'ip'=>  $ip,
        );
        
        M('Msglog')->add($add_msglog);

        if ($res > 0) {
            // user_id = 0 user_name = admin  表示为系统发送,短信的条数不做操作
            if ($user_id != 0) {
                M('Msglog')->where('user_id=' . $user_id)->setDec('num');
            }
            return true;
            
        } else {
            render('10002', '短信发送失败!');
        }
    }
    /**
     * 生成随机码 用于注册 以及修改
     */
    function make_code() {
        $chars = '0123456789';
        $code = '';
        for ($i = 0; $i < 4; $i++) {
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $code;
    }
    /**
     * 系统发送短信，包含 注册   修改手机号  等信息
     */
    function send_msg_system($type, $to_mobile) {
        $mcode = $this->make_code();
        if ($type == 'register') {
            //注册发送短信的内容
//            $smsText = "您的注册验证码是:" . $mcode . ".请不要把验证码泄露给其他人.";
            $smsText = "您的验证码是:" . $mcode . ".请不要把验证码泄露给其他人.";
        } else if ($type == 'change') {
            //修改发送的短信内容
            $smsText = "您的修改验证码是:" . $mcode . ".请不要把验证码泄露给其他人.";
        } else if ($type == 'find') {
            //找回密码发送的短信内容
            $smsText = "您的找回密码验证码是:" . $mcode . ".请不要把验证码泄露给其他人.";
        } else if ($type == 'login') {
            //找回密码发送的短信内容
            $smsText = "您的登录验证码是:" . $mcode . ".请不要把验证码泄露给其他人.";
        }
        //存入session 做认证
        unset($_SESSION['MobileConfirmCode']);
        $_SESSION['MobileConfirmCode'] = $mcode;
        $this->send_msg(0, 'admin', $to_mobile, $smsText);
        return true;
    }
    /**
     * 关于订单的短信发送,此发送需要扣除卖家的短信条数
     */
    function send_msg_order($order_info, $type) {
        $msg = M('msg')->where("user_id=" . $order_info['seller_id'])->find();
        /**
         * 检测是否有权限
         */
        $result = $this->check_functions($msg, $type);
        if($result['done']==FALSE){
            return $result;
        }
        
        $user_id = $order_info['seller_id'];
        $user_name = $order_info['seller_name'];

        if ($type == 'check') {
            //买家确认收货向卖家发送短信提示
            $to_mobile = $msg['mobile'];
            $smsText = "您的订单：" . $order_info['order_sn'] . "，买家" . $order_info['buyer_name'] . "已经确定！"; //内容
        } else if ($type == 'buy') {
            //买家下单向卖家发送短信提示
            $to_mobile = $msg['mobile'];
            $smsText = "您收到了来自买家" . $order_info['buyer_name'] . "的订单，订单号为：" . $order_info['order_sn'] . "，请及时处理！"; //内容
        } else if ($type == 'send') {
            //卖家发货向买家发送短信提示
            $row_order_extm = M('OrderExtm')->where("order_id=" . $order_info['order_id'])->find();
            $to_mobile = $row_order_extm['phone_mob'];

            $smsText = "您的订单：" . $order_info['order_sn'] . ",卖家：" . $order_info['seller_name'] . "已经发货，请及时查收！"; //内容
        } else {
            return array('done' => FALSE ,'msg' => '发送验证码1分钟只能点击发送1次',);
        }
        
        $result = $this->send_msg($user_id, $user_name, $to_mobile, $smsText);
        return $result;
    }


    /**
     * 检测是否具有发送短信条件
     * 
     */
    function check_functions($msg, $type = '') {
        $functions = $this->get_functions();
        $tmp = explode(',', $msg['functions']);
        if ($functions) {
            foreach ($functions as $func) {
                $checked_functions[$func] = in_array($func, $tmp);
            }
        }
        //卖家未开启支付
        if ($msg['state'] == 0) {
            return array('done' => FALSE ,'msg' => '卖家未开启短信功能',);
        }
        if($type) {
            //卖家未开启 确认收货发送短信
            if (!$checked_functions[$type]) {
                return array('done' => FALSE ,'msg' => '卖家未开启此短信方式',);
            }
        }
        //卖家可用短信数 不够
        if ($msg['num'] <= 0) {
            return array('done' => FALSE ,'msg' => '卖家可用短信数不够',);
        }
        return array('done' => TRUE ,'msg' => '发送成功',);
    }
    /**
     *    获取可用功能列表
     *
     *    @author    andcpp
     *    @return    array
     */
    function get_functions() {
        $arr = array();
        $arr[] = 'buy'; //来自买家下单通知   
        $arr[] = 'send'; //卖家发货通知买家   
        $arr[] = 'check'; //来自买家确认通知   
        return $arr;
    }
}

?>
